<template>
  <el-alert
          title="提示"
          type="warning"
          description="请仔细核验登记信息"
          show-icon
  />
  <div style="margin-top: 20px">
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="资产名称" prop="zcmc">
            <el-input v-model="form.zcmc" placeholder="请输入资产名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="资产类别" prop="typeId">
            <el-select v-model="form.typeId" placeholder="请选择资产设备类别">
              <el-option
                      v-for="item in selectAssetTypeOptionData"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="资产型号" prop="zcxh">
            <el-input v-model="form.zcxh" placeholder="请输入资产型号"/>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="资产数量" prop="zcsl">
            <el-input-number v-model="form.zcsl" :min="0"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="资产单价" prop="zcdj">
            <el-input v-model="form.zcdj" placeholder="请输入资产单价"/>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="资产金额" prop="zcje">
            <el-input v-model="form.zcje" placeholder="请输入资产金额"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="生厂厂家" prop="sccj">
            <el-input v-model="form.sccj" placeholder="请输入生产厂家"/>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="生产日期" prop="scrq">
            <el-date-picker v-model="form.scrq" type="date" placeholder="请选择生产日期" style="width: 100%"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="购买日期" prop="gmrq">
            <el-date-picker v-model="form.gmrq" type="date" placeholder="请选择购买日期" style="width: 100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <!-- 上传合同 -->
          <el-form-item label="购买人" prop="gmr">
            <el-select v-model="form.gmr" placeholder="请选择购买人">
              <el-option v-for="item in selectStaffOptionData" :label="item.name" :value="item.id" :key="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="10">
          <!-- 上传合同 -->
          <el-form-item label="上传合同">
            <el-upload
                    ref="uploadRef"
                    class="upload-demo"
                    :auto-upload="false"
                    accept=".pdf"
                    :show-file-list="false"
                    :file-list="filesList"
                    :on-change="handleChange"
            >
              <el-button type="primary">上传</el-button>
              <p style="margin-left: 15px;color: #99a9bf">{{ upload_file }}</p>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 提交按钮 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <div style="margin-left: 50px">
            <el-button type="primary" @click="onSubmit()">登记</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { getCurrentInstance, ref } from 'vue';
import request, { getServerUrl } from "@/util/request";
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import router from "@/router";

const {proxy} = getCurrentInstance()

const formRef = ref(null);

/**
 * 定义变量
 */
const form = ref({
  zcmc: "",
  typeId: "",
  zcxh: "",
  zcsl: 0,
  zcdj: "",
  zcje: "",
  sccj: "",
  scrq: "",
  gmrq: "",
  gmr: "",
})

/**
 * 表单校验规则
 */
const rules = ref({
  zcmc: [{required: true, trigger: "blur", message: "请输入资产名称"}],
  typeId: [
    {required: true, trigger: "blur", message: "请选择资产类别"}
  ],
  zcxh: [{required: true, trigger: "blur", message: "请填写资产型号"}],
  zcsl: [{required: true, trigger: "blur", message: "请填写资产数量"}],
  zcdj: [{required: true, trigger: "blur", message: "请填写资产单价"}],
  zcje: [{required: true, trigger: "blur", message: "请填写资产金额"}],
  sccj: [{required: true, trigger: "blur", message: "请填写生厂厂家"}],
  scrq: [{required: true, trigger: "blur", message: "请选择生产日期"}],
  gmrq: [{required: true, trigger: "blur", message: "请选择购买日期"}],
  gmr: [{required: true, trigger: "blur", message: "请选择购买人"}],
})

/**
 * 遍历所有的资产类别信息
 */
const selectAssetTypeOptionData = ref([]);
const getAssetType = async () => {
  const res = await request.get("assetType/list");
  selectAssetTypeOptionData.value = res.data.assetTypeList;
}
getAssetType();

/**
 * 遍历所有的员工信息
 */
const selectStaffOptionData = ref([]);
const getStaffOffice = async () => {
  const res = await request.get("staff/listOffice");
  selectStaffOptionData.value = res.data.staffOfficeList;
}
getStaffOffice();

const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log(upload_file.value)
      if (upload_file.value === "只允许上传PDF文件") {
        ElMessage({
          type: 'error',
          message: '请上传合同',
        })
      } else {
        ElMessageBox.confirm(
                '请检查无误后提交，确定登记如下信息吗？',
                '提示',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                }
        )
                .then(async () => {
                  const res = await request.post("asset/save", form.value);
                  const param = new FormData();
                  filesList.value.forEach((val) => {
                            param.append("file", val.raw);
                          }
                  );

                  if (res.data.code === 200) {
                    const fileRes = await request.post("asset/uploadContract", param);
                    handelReceive(form.value.zcmc, fileRes.data.title)
                    if (fileRes.data.code === 200) {
                      const saveRes = await request.post("asset/saveByName", saveData.value);
                      if (saveRes.data.code === 200) {
                        ElMessage({
                          type: 'success',
                          message: '登记成功',
                        })
                        await router.replace("/assetsIndex")
                      } else {
                        ElMessage({
                          type: 'error',
                          message: '登记失败',
                        })
                      }
                    }
                  }
                })
      }
    } else {
      ElMessage.error("请填写详细信息")
    }
  })
}

const headers = ref({
  token: window.sessionStorage.getItem("token")
})

const upload_file = ref("只允许上传PDF文件");

const filesList = ref([]);

const handleChange = (file, fileList) => {
  if (!/\.(pdf)$/.test(file.name.slice(file.name.lastIndexOf('.')))) {
    ElNotification({
      title: '错误！！',
      message: '上传格式不正确，请上传PDF文件',
      type: 'error',
    })
    proxy.$refs.uploadRef.handleRemove(file);
  } else {
    ElNotification({
      title: '成功！！',
      message: '上传成功',
      type: 'success',
    })
    upload_file.value = file.name;
    filesList.value = fileList.splice(-1);
  }
}

const saveData = ref({
  zcmc: "",
  cght: ""
})
const handelReceive = (name, contract) => {
  saveData.value.zcmc = name;
  saveData.value.cght = contract;
}
</script>

<style lang="scss" scoped>
.upload_box {
  position: relative;

  div {
    padding: 0 15px 0 15px;
    height: 35px;
    line-height: 35px;
    text-align: center;
    background-color: #419fff;
    border-radius: 5px;
    z-index: 1;

    span {
      color: white;
      letter-spacing: 1px;
      font-size: 14px;
    }
  }

  .upload_file {
    position: absolute;
    top: 5px;
    left: 0;
    width: 160px;
    height: 44px;
    opacity: 0;
    cursor: pointer;
  }
}
</style>